package com.gan.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gan.ganapicommon.model.entity.InterfaceInfo;
import com.gan.ganapicommon.model.entity.UserInterfaceInfo;
import com.gan.project.common.BaseResponse;
import com.gan.project.common.ErrorCode;
import com.gan.project.common.ResultUtils;
import com.gan.project.exception.BusinessException;
import com.gan.project.mapper.InterfaceInfoMapper;
import com.gan.project.mapper.UserInterfaceInfoMapper;
import com.gan.project.model.vo.InterfaceInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author gan
 * @date 2023/5/9 16:41
 * 分析控制器
 */
@RestController
@RequestMapping("/analysis")
@Slf4j
public class AnalysisController {

    @Resource
    private UserInterfaceInfoMapper userInterfaceInfoMapper;

    @Resource
    private InterfaceInfoMapper interfaceInfoMapper;


    @GetMapping("/top/interface/invoke")
    //@AuthCheck(mustRole = "admin")
    public BaseResponse<List<InterfaceInfoVO>> getTopInterfaceInfo (){
        List<UserInterfaceInfo> topInterfaceInfo = userInterfaceInfoMapper.getTopInterfaceInfo(3);
        // 用stream中的分组器将某个字段分出来
        Map<Long, List<UserInterfaceInfo>> interfaceIds =
                topInterfaceInfo.stream().collect(Collectors.groupingBy(UserInterfaceInfo::getInterfaceInfoId));
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",interfaceIds.keySet());
        List<InterfaceInfo> list = interfaceInfoMapper.selectList(queryWrapper);
        if (list == null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        // 把一个类型映射成另一个类型,用collect收集
        List<InterfaceInfoVO> lists = list.stream().map(interfaceInfo -> {
            InterfaceInfoVO interfaceInfoVO = new InterfaceInfoVO();
            BeanUtils.copyProperties(interfaceInfo, interfaceInfoVO);
            int totalNum = interfaceIds.get(interfaceInfo.getId()).get(0).getTotalNum();
            interfaceInfoVO.setTotalNum(totalNum);
            return interfaceInfoVO;
        }).collect(Collectors.toList());
        return ResultUtils.success(lists);
    }

}
